import SwiftUI
import Combine

struct UserListView: View {

    @ObservedObject var viewModel: UserListViewModel

    var body: some View {
        List(viewModel.users) { user in
            VStack(alignment: .leading) {
                Text(user.name)
                    .font(.headline)
                Text(user.email)
                    .font(.subheadline)
            }
        }
        .onAppear() {
            self.viewModel.fetchUsers()
        }
    }
}

class UserListViewModel: ObservableObject {

    @Published var users = [User]()
    
    func fetchUsers() {
        provider.request(.getUsers) { result in
            switch result {
            case let .success(response):
                do {
                    let decoder = JSONDecoder()
                    let users = try decoder.decode([User].self, from: response.data)
                    DispatchQueue.main.async {
                        self.users = users
                    }
                } catch let error {
                    print(error)
                }
            case let .failure(error):
                print(error)
            }
        }
    }
    func test(){
        provider.request(.test){ result in
            switch result {
            case let .success(response):
                do {
                    let data = response.data
                    let str = String(data: data, encoding: .utf8)
                    print(str)
                    
                }
              //  todo:如何转成json对象
//                    guard let data = try response.mapJSON() as? [String: Any],
//                                          let jsonData = try? JSONSerialization.data(withJSONObject: data, options: .prettyPrinted),
//                                          let jsonString = String(data: jsonData, encoding: .utf8)
//                    else {
//                                        print("Failed to convert response to JSON object")
//                                        return
//                                    }
//                                    print(jsonString)
//
//                }catch(let error) {
//                    print(error)
//                }
            case let .failure(error):
                print(error)
            }
        }
    }
}

struct User: Codable, Identifiable {
    let id: Int
    let name: String
    let email: String
}
